package com.hevery.web.async;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * @author: zhy
 * @description: 队列的一个监听器，用于监听虚拟的消息队列，实现ApplicationListener，监听ContextRefreshedEvent事件(整个Spring容器初始化完毕的事件)
 * @date: created on 2017/10/20
 * @modified by:
 */
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent>{

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * onApplicationEvent相当于当整个系统起起来之后要做的事：即监听模拟的消息队列中CompleteOrder的值
     * @param contextRefreshedEvent
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        /**此处需要单开线程，因为当前代码是在应用的启动过程中执行的，会有一个无限的while循环，
         * 如果不单开线程的话就会阻塞整个系统的启动*/
        new Thread(() -> {
            while (true){
                if(StringUtils.isNotBlank(mockQueue.getCompleteOrder())){
                    String orderNumber = mockQueue.getCompleteOrder();
                    logger.info("返回订单处理结果："+orderNumber);
                    /**通过订单号拿到一个DeferredResult，然后调setResult方法，表示整个异步处理完成，往浏览器返回结果*/
                    deferredResultHolder.getMap().get(orderNumber).setResult("place order success");
                    /**避免反复处理同一个订单*/
                    mockQueue.setCompleteOrder(null);
                }else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }
}
